// Package redis pkg/redis/redis.go
package redis

import (
	"context"
	"github.com/go-redis/redis/v8"
	"github.com/spf13/viper"
	"time"
)

// InitRedis 初始化连接
func InitRedis() (*redis.Client, error) {

	rdb := redis.NewClient(&redis.Options{
		Addr:     viper.GetString("redis.address"),
		Password: viper.GetString("redis.password"),
		DB:       viper.GetInt("redis.db"),
		//DialTimeout:  viper.GetTime("redis.dial_timeout"),
		//ReadTimeout:  viper.GetString("redis.read_timeout"),
		//WriteTimeout: viper.GetString("redis.write_timeout"),
	})

	// 测试连接
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	_, err := rdb.Ping(ctx).Result()
	if err != nil {
		return nil, err
	}

	return rdb, nil
}
